<?php
namespace app\controllers;

use app\controllers\common\BaseController;

use app\models\Role;
use app\models\Access;

use yii;
/**
 * 
 */
class AccessController extends BaseController
{
	

	public function actionIndex(){
		if( yii::$app->request->isGet ){
			$list = Access::find()->where(['status'=>1])->all();
			return $this->render('index',['list'=>$list]);
		}
	}


	public function actionSet(){
		if( yii::$app->request->isGet ){
			$id = $this->get('id',0);
			$info = [];
			if( $id ){
				$info = Access::find()->where(['status'=>1,'id'=>$id])->one();
			}

			return $this->render('set',['info'=>$info]);
		}
		$id = intval($this->post('id',0));
		$title = trim($this->post('title',''));
		$url = trim($this->post('urls',''));
		$urls = explode("\n",$url);
		$date_now = date('Y-m-d H:i:s');
		if( mb_strlen($title,'utf8')<1 || mb_strlen($title,'utf-8')>20 ){
			return $this->renderJSON([],'请输入合法权限标题',-1);
		}
		if( !$urls ){
			return $this->renderJSON([],'请输入合法权限url',-1);	
		}
		if(! $urls){
			return $this->renderJSON([],'请输入合法权限urls',-1);		
		}
		/* 查询标题是否存在  */
		$info  = Access::find()->where(['title'=>$title])->andWhere(['!=','id',$id])->one();
		if( $info ){
			return $this->renderJSON([],'标题已存在',-1);
		}
		/* 查询这个id对应的权限是否存在，存在则编辑，反之添加 */
		$acc_info = Access::find()->where(['id'=>$id])->one();

		if( !$acc_info ){
			$access = new Access();
			$access->create_time = $date_now;
			$access->status = 1;
		}else{/*  编辑操作*/
			$access = $acc_info;
		}
		$access->title = $title;
		$access->urls = json_encode($urls);
		$access->update_time = $date_now;
		$access->save(0);
		return $this->renderJSON([],'操作成功');


	}
	
}
